import $ from 'jquery'
import {serverUrl} from "../../js/base";

export function POST(url, data, options) {
    return ajax(url, data, options, 'post')
}

export function DELETE(url, data, options) {
    return ajax(url, data, options, 'delete')
}

export function GET(url, data, options) {
    return ajax(url, data, options, 'get')
}

export function PUT(url, data, options) {
    return ajax(url, data, options, 'put')
}

function ajax(url, data, options, requestType) {
    return $.ajax({
        url: `${serverUrl}${url}`,
        data: JSON.stringify(data),
        contentType: 'application/json',
        dataType: 'json',
        ...options,
        type: requestType,
        beforeSend(xhr) {
            xhr.setRequestHeader('USER-TOKEN', 'admin')
        },
        dataFilter(data) {
            return data
        },
        async success(data) {
            await data
        },
        async error(err) {
            console.error(err)
            await err
        },
        complete(data) {
            // console.log('complete', data)
        }
    })
}

export default {
    POST,
    DELETE,
    GET,
    PUT
}
